/*
 * Copyright (C) 2011, EADS France
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */
package xowl.interpreter.backends.rdf;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Laurent WOUTERS
 */
public abstract class RDFQueryEngine extends xowl.interpreter.impl.QueryEvaluator implements RDFChangeListener {
    protected RDFRepository repository;
    protected xowl.interpreter.backends.rete.RETENetwork network;
    protected List<RDFChange> changes;
    protected boolean applyingChanges;
    
    public RDFQueryEngine(RDFRepository repo) {
        this.repository = repo;
        this.network = new xowl.interpreter.backends.rete.RETENetwork();
        this.changes = new ArrayList<RDFChange>();
    }
    
    @Override public void onChange(xowl.interpreter.impl.AggregatedEvaluator evaluator, RDFChange change) { changes.add(change); }
    @Override public void onChanges(xowl.interpreter.impl.AggregatedEvaluator evaluator, RDFChangeset changeset) {
        for (RDFChange change : changeset.getRDFChanges())
            changes.add(change);
    }
    
    protected void applyChanges() {
        if (applyingChanges)
            return;
        applyingChanges = true;
        while (!changes.isEmpty()) {
            List<RDFChange> buffer = new ArrayList<RDFChange>(changes);
            changes.clear();
            for (RDFChange change : buffer)
                network.inject(change);
        }
        applyingChanges = false;
    }
}
